package com.vic.framework.helper;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.vic.framework.utils.ReflectionUtil;

/**
 * Bean辅助类
 * @author VIC
 *
 */
public final class BeanHelper {
	
	/**
	 * Bean映射 bean类-->bean实例
	 */
	private static final Map<Class<?>, Object> BEAN_MAP = new HashMap<Class<?>, Object>();

	static {
		Set<Class<?>> classSet = ClassHelper.getBeanClassSet();
		
		for(Class<?> cls : classSet) {
			Object obj = ReflectionUtil.newInstance(cls);
			BEAN_MAP.put(cls, obj);
		}
	}
	
	/**
	 * 增加bean 也可能是替换
	 */
	public static void setBean(Class<?> cls, Object obj) {
		BEAN_MAP.put(cls, obj);
	}
	
	/**
	 * 获取bean映射
	 */
	public static Map<Class<?>, Object> getBeanMap(){
		return BEAN_MAP; 
	}
	
	/**
	 * 获取bean实例
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(Class<T> cls) {
		if(!BEAN_MAP.containsKey(cls)) {
			throw new RuntimeException("cannot get bean by class:" + cls);
		}
		return (T) BEAN_MAP.get(cls);
	}
	
	
	
	
}


